package cn.liberals.controller;

import cn.liberals.domain.User;
import cn.liberals.handler.UserFallBackHandler;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RefreshScope  //刷新配置
public class UserController {

    @Value("${test}")
    private Long test;

    /*
        1.sentinel有五种规则我们可以配置
        2.当触发了配置的规则 那么sentinel会抛出blockException
        3.当配置了blockHandler的时候 那么就会捕获blockException 并进入指定的方法
        4.当配置了fallback,那么程序出现异常 就会进入指定的方法
        5.如果fallback和blockHandler同时触发 那么会进到blockHandler指定的方法
     */
    @GetMapping("/getUserById/{id}")
    @SentinelResource(value = "getUserById" ,
            blockHandler  = "getUserByIdBlockHandler" ,
            blockHandlerClass  = UserFallBackHandler.class,
            fallback = "getUserByIdFallBack")
    public User getUserById(@PathVariable Long id){
        int i = 1/0;
        return User.builder().id(test).username("小小杏").intro("所噶").build();
    }

    public static User getUserByIdFallBack(@PathVariable Long id , Throwable t){
        return User.builder().id(-2l).intro("fallback").username("fallback").build();
    }

}
